package m.toolkit.console;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 保存正在执行的命令,每隔5分钟移除完结状态的命令
 * 
 * @author ming
 * @date 2014年2月23日下午2:50:13
 */
public class CommandExecutorHolder {
	private static Logger log = LoggerFactory.getLogger(CommandExecutorHolder.class);
	// 当前正在执行的命令
	private Map<String, CommandExecutor> map = new ConcurrentHashMap();
	// 一个命令最多允许执行1分钟,超过的强行停止
	private long maxReamin = 1000 * 60;
	private long scan=1000*60*5;

	public CommandExecutorHolder() {
		new Thread() {
			public void run() {
				while(true){
					try{
						monitor();
						Thread.sleep(scan);
					}catch(Exception ex){
						log.error("扫描监控任务时出错",ex);
					}
					
				}
			}
		}.start();
	}
	
	
	public void monitor(){
		List<String> preRemoveKey = new ArrayList();
		Set<Entry<String, CommandExecutor>> set = map.entrySet();
		for (Entry<String, CommandExecutor> en : set) {
			CommandExecutor c = en.getValue();
			Command cmd = c.getCommand();
			switch (cmd.getStatus()) {
			//清理5分钟前完结状态的
			case 中止:
			case 取消:
			case 失败:
			case 成功:
				long end=System.currentTimeMillis()-cmd.getEndTime();
				if(end>=1000*60*5){
					preRemoveKey.add(en.getKey());
				}
				break;
			case 执行中:
				long remain=System.currentTimeMillis()-cmd.getBeginTime();
				if(remain>=maxReamin){
					c.stop();
					preRemoveKey.add(en.getKey());
				}
				break;
			default:
				break;
			}
		}
		
		//开始删除了
		for(String s :preRemoveKey){
			map.remove(s);
		}
	}

	public void put(String commandId, CommandExecutor cmdEx) {
		map.put(commandId, cmdEx);
	}

	public CommandExecutor get(String commandId) {
		return map.get(commandId);
	}

}
